<?php
require_once ('../paths.php');
require_once (CONFIG.'config.php'); 
require_once (DB.'general.db.php');
require_once (INCLUDES.'url_variables.inc.php');

//error_reporting(E_ALL);
//ini_set('display_errors', '1');

session_start(); 
//require ('authentication.inc.php'); session_start(); sessionAuthenticate();

function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;
  require ('scrubber.inc.php');
  switch ($theType) {
  
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
	case "scrubbed":
	  $theValue = ($theValue != "") ? "'" . strtr($theValue, $html_string) . "'" : "NULL";
  }
  return $theValue;
}

if ($action != "delete") { // Record the date, time and location of the last update by a user
	$date_time = date("F j, Y - g:i a");
	$url_last = str_replace("&saved=true", "", $_POST['url_last']);
	if (strstr($url_last, "&msg")) {
		$url_last = str_replace("&msg=", "", $url_last);
		$url_last = rtrim ($url_last, "123456789");
	}
$updateSQL = sprintf("UPDATE users SET url_last=%s, url_title_last=%s, time_last=%s, course_num=%s  WHERE id=%s", 
			GetSQLValueString($url_last, "text"),
			GetSQLValueString($_POST['url_title_last'], "text"),
			GetSQLValueString($date_time, "text"),
			GetSQLValueString($_POST['course_num'], "text"),
			GetSQLValueString($_POST['user_id'], "int")
		);						
mysql_select_db($database, $connection);
$result_update = mysql_query($updateSQL, $connection) or die(mysql_error());

$updateSQL = sprintf("UPDATE courses SET updated=%s, user_id=%s  WHERE id=%s", 
			GetSQLValueString($date_time, "text"),
			GetSQLValueString($_POST['user_id'], "int"),
			GetSQLValueString($cid, "int")
		);						
mysql_select_db($database, $connection);
$result_update = mysql_query($updateSQL, $connection) or die(mysql_error());

if ($action == "save") {
	$updateGoTo = $_POST['url_last']."&saved=true";
	//echo $updateGoTo;
	header(sprintf("Location: %s", $updateGoTo));
	}
if ($action == "logout") {
	$updateGoTo = "logout.inc.php";
	//echo $updateGoTo;
	header(sprintf("Location: %s", $updateGoTo));
	}
}

if ($action == "delete") {
$deleteSQL = sprintf("DELETE FROM $dbTable WHERE id='%s'", $id);
//echo $deleteSQL."<br>";
mysql_select_db($database, $connection);
$Result1 = mysql_query($deleteSQL, $connection) or die(mysql_error());

if ($dbTable == "courses") { 
// Delete all data associated with the designated course

$a = array("assignments","comments","course_description","course_project","learning_outcomes","materials","modules","project_deliverable","readings","rubrics","standard_mapping","themes");
	foreach($a as $value) {
	// find all rows in the named table that are associated with the course
	$query_cid = sprintf("SELECT id FROM %s WHERE cid='%s'", $value, $id);
	$cid = mysql_query($query_cid, $connection) or die(mysql_error());
	$row_cid = mysql_fetch_assoc($cid);
	$totalRows_cid = mysql_num_rows($cid);
	//echo "<p>".$query_cid."<br>";
		if ($totalRows_cid > 0) { 
			do { 
			// loop through the table deleting all the found rows
			$deleteValue = sprintf("DELETE FROM %s WHERE id='%s'", $value, $row_cid['id']);
			mysql_select_db($database, $connection);
			$Result2 = mysql_query($deleteValue, $connection) or die(mysql_error());
			//echo $deleteValue."<br>";
			} while ($row_cid = mysql_fetch_assoc($cid));
		}
	}
}

if (strstr($_SERVER['HTTP_REFERER'], "&msg")) { $deleteGoTo = rtrim($_SERVER['HTTP_REFERER'], "123456789"); $deleteGoTo .= "9";}
else { $deleteGoTo = $_SERVER['HTTP_REFERER']; $deleteGoTo .= "&msg=9"; }
//echo $deleteGoTo;

header(sprintf("Location: %s", $deleteGoTo));
}

if ($action != "delete") {
	
	$url_last = str_replace("&saved=true", "", $_POST['url_last']);
		if (strstr($url_last, "&msg")) {
			$url_last = str_replace("&msg=", "", $url_last);
			$url_last = rtrim ($url_last, "123456789");
		}
	$insertGoTo = $url_last;
	$updateGoTo = $url_last;

	// ---------------------------If Adding/Editing Readings ------------------------------- //
	
	if ($dbTable == "readings") { 
		include (INCLUDES.'process_comments.inc.php');
		include (PROCESS.'process_readings.inc.php');
	}
	
	// --------------------------- If Adding/Editing the Course Description ------------------------------- //
	
	if ($dbTable == "course_description") {
		include (INCLUDES.'process_comments.inc.php');
		include (PROCESS.'process_course_description.inc.php');
	}
	
	// --------------------------- If Adding/Editing a Course Project Description ------------------------------- //
	
	if ($dbTable == "course_project") {
		include (INCLUDES.'process_comments.inc.php');
		include (PROCESS.'process_course_project.inc.php');
	}
	
	// --------------------------- If Adding/Editing a Project Deliverable ------------------------------- //
	
	if ($dbTable == "project_deliverable") {
		include (INCLUDES.'process_comments.inc.php');
		include (PROCESS.'process_project_deliverable.inc.php');
	}
	
	// --------------------------- If Adding/Editing Associated Learning Outcomes ------------------------------- //
	
	if ($dbTable == "learning_outcomes") { 
		include (INCLUDES.'process_comments.inc.php');
		include (PROCESS.'process_learning_outcomes.inc.php');
	}
	
	// --------------------------- If Adding/Editing Course Materials ------------------------------- //
	
	if ($dbTable == "materials") { 
		include (INCLUDES.'process_comments.inc.php');
		include (PROCESS.'process_materials.inc.php');
	}
	
	// --------------------------- If Adding/Editing Theme Conent ------------------------------- //
	
	if ($dbTable == "themes") { 
		include (INCLUDES.'process_comments.inc.php');
		include (PROCESS.'process_themes.inc.php');
	}
	
	// --------------------------- If Adding/Editing Assignment Conent ------------------------------- //
	
	if ($dbTable == "assignments") { 
		include (INCLUDES.'process_comments.inc.php');
		include (PROCESS.'process_assignments.inc.php');
	}
	
	// --------------------------- If Adding/Editing Courses ------------------------------- //
	
	if ($dbTable == "courses") {
		include (PROCESS.'process_courses.inc.php');
	}
	
	// --------------------------- Adding/Editing Module, Assignment, and Theme Titles  ------------------------------- //

	if ((($dbTable == "modules") || ($dbTable == "themes") || ($dbTable == "assignments")) && ($section == "proposal_titles")) {
		include (PROCESS.'process_titles.inc.php');
	}

if ($action == "email") { 
// Gather the variables from the form
$to_email = $_POST['to_email'];
$to_name = $_POST['to_name'];
$from_email = $_POST['from_email'];
$from_name = $_POST['from_name'];
$subject = $_POST['jiu_course_id']." Proposal";
$message_post = $_POST['message'];

// Build the message
$message = "<html>" . "\r\n";
//$message .= "<head>" . $subject."</head>" . "\r\n";
$message .= "<body>" . $message_post. "\r\n". "</body>" . "\r\n";
$message .= "</html>";

$headers  = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "To: ".$to_name." <".$to_email.">, " . "\r\n";
$headers .= "From: ".$from_name." <".$from_email.">" . "\r\n";
//$headers .= "CC: ".$from_name." <".$from_email.">" . "\r\n";

// Debug
//echo $headers."<br>";
//echo $message;

mail($to_email, $subject, $message, $headers);
header("Location: ../index.php?section=".$section."&action=email&cid=".$cid."&msg=2");
}



// --------------------------- If Adding User (and ID or CE) ------------------------------- //


if (($action == "add") && ($dbTable == "users")) {
// Check to see if username address is already in the system. If so, redirect.
$username = $_POST['user_name'];

mysql_select_db($database, $connection);
$query_userCheck = "SELECT user_name FROM users WHERE user_name = '$username'";
$userCheck = mysql_query($query_userCheck, $connection) or die(mysql_error());
$row_userCheck = mysql_fetch_assoc($userCheck);
$totalRows_userCheck = mysql_num_rows($userCheck);

if ($totalRows_userCheck > 0) {
  header("Location: ../index.php?section=".$section."&action=view&msg=2");
  }
  else 
  {
  $password = md5($_POST['password']);
  $insertSQL = sprintf("INSERT INTO users (user_name, userLevel, password, firstName, lastName, email, phone) VALUES (%s, %s, %s, %s, %s, %s, %s)", 
                       GetSQLValueString($username, "text"),
					   GetSQLValueString($_POST['userLevel'], "text"),
                       GetSQLValueString($password, "text"),
					   GetSQLValueString($_POST['firstName'], "text"),
					   GetSQLValueString($_POST['lastName'], "text"),
					   GetSQLValueString($_POST['email'], "text"),
					   GetSQLValueString($_POST['phone'], "text")
					   );
  	mysql_select_db($database, $connection);
  	$Result1 = mysql_query($insertSQL, $connection) or die(mysql_error());

	$insertGoTo = "../index.php?section=".$section."&action=view&msg=1";
	header(sprintf("Location: %s", $insertGoTo));
	}
}
// --------------------------- If Editing a Participant ------------------------------- //


if (($action == "edit") && ($dbTable == "users")) {
if ($go == "default") {
$updateSQL = sprintf("UPDATE users 
			SET 
			firstName=%s, 
			lastName=%s, 
			user_name=%s,
			phone=%s,
			email=%s 
			WHERE id=%s", 
				GetSQLValueString($_POST['firstName'], "text"),
				GetSQLValueString($_POST['lastName'], "text"),
				GetSQLValueString($_POST['user_name'], "text"),
				GetSQLValueString($_POST['phone'], "text"),
				GetSQLValueString($_POST['email'], "text"),
				GetSQLValueString($id, "int")
			);
  						
		mysql_select_db($database, $connection);
  		$result1 = mysql_query($updateSQL, $connection) or die(mysql_error());
		
		$updateGoTo = "../index.php?section=".$section."&action=view&msg=4";
		header(sprintf("Location: %s", $updateGoTo));
}
// --------------------------- If Changing a Paricipant's Password ------------------------------- //
if ($go == "password") {

// Check if old password is correct; if not redirect
$passwordNew = md5($_POST['password']); 
  $updateSQL = sprintf("UPDATE users SET password=%s WHERE id=%s", 
                       GetSQLValueString($passwordNew, "text"),
                       GetSQLValueString($id, "int")); 

  mysql_select_db($database, $connection);
  $Result1 = mysql_query($updateSQL, $connection) or die(mysql_error());
  $updateGoTo = "../index.php?section=".$section."&action=view&saved=".$_POST['password']."&id=".$id."&msg=3";
  header(sprintf("Location: %s", $updateGoTo));
 }

}

if (($action == "make_admin") && ($dbTable == "users")) {
$updateSQL = sprintf("UPDATE users SET userLevel=%s WHERE id=%s", 
                       GetSQLValueString($go, "int"),
                       GetSQLValueString($id, "int")); 

mysql_select_db($database, $connection);
$Result1 = mysql_query($updateSQL, $connection) or die(mysql_error());
$updateGoTo = "../index.php?section=".$section."&action=view&msg=4";
//echo $updateSQL."<br>";
//echo $updateGoTo;
header(sprintf("Location: %s", $updateGoTo));

}

} // end if (action != delete)
?>